<% layout('/layouts/default.html', {title: '编码规则管理', libs: ['validate','dataGrid']}){ %>
<div class="main-content">
	<div class="box box-main">
		<div class="box-header with-border">
			<div class="box-title">
				<i class="fa icon-note"></i> ${text(codingRuleHeader.isNewRecord ? '新增编码规则' : '编辑编码规则')}
			</div>
			<div class="box-tools pull-right hide">
				<button type="button" class="btn btn-box-tool" data-widget="collapse"><i class="fa fa-minus"></i></button>
			</div>
		</div>
		<#form:form id="inputForm" model="${codingRuleHeader}" action="${ctx}/codingrule/header/save" method="post" class="form-horizontal">
			<div class="box-body">
				<div class="form-unit hide">${text('基本信息')}</div>
				<#form:hidden path="autoId"/>
				<#form:hidden path="orgId"/>
				<#form:hidden path="orgCode"/>
				<#form:hidden path="orgName"/>
				<div class="row">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required ">*</span> ${text('对象类型')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-4">
								<#form:select id="objectType" path="objectType" items="${objectTypeEnum}" itemLabel="name" itemValue="code" class="form-control required" readonly="${!codingRuleHeader.isNewRecord}"/>
							</div>
						</div>
					</div>
					<div id="barcodeTypeHide">
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required">*</span> ${text('条码类型')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-4">
								<#form:select id="barcodeType" path="barcodeType" items="${barcodeTypeEnum}" blankOption="true" itemLabel="name" itemValue="code" class="form-control" readonly="${!codingRuleHeader.isNewRecord}"/>
							</div>
						</div>
					</div>
					</div>
					<div id="formIdHide">
						<div class="col-xs-12">
							<div class="form-group">
								<label class="control-label col-sm-2" title="">
									<span class="required ">*</span> ${text('表单名称')}：<i class="fa icon-question hide"></i></label>
								<div class="col-sm-4">
									<#form:select id="formId" path="formId" items="${formList}" itemLabel="name" itemValue="id"
									blankOption="true" class="form-control"
									readonly="${!codingRuleHeader.isNewRecord}"/>
								</div>
							</div>
						</div>
					</div>
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required ">*</span> ${text('编码方式')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-4">
								<#form:select id="codingType" path="codingType" items="${codingTypeEnum}" itemLabel="name" itemValue="code" blankOption="true" blankOptionValue="0" class="form-control" readonly="${!codingRuleHeader.isNewRecord}"/>
							</div>
						</div>
					</div>
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="详情配置">
								<span class="required hide">*</span> ${text('详情配置')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-10">
								<div class="table-form ">
									<% if (hasPermi('codingrule:header:edit')){ %>
									<a href="#" id="linesDataGridAddRowBtn" class="btn btn-primary btn-sm mt10 mb10"><i class="fa fa-plus"></i> 增行</a>
									<% } %>
									<table id="linesDataGrid"></table>
								</div>
							</div>
						</div>
					</div>
					<div class="col-xs-12">
						<div class="form-group">
							<label class="control-label col-sm-2" title="">
								<span class="required hide">*</span> ${text('编码示例')}：<i class="fa icon-question hide"></i></label>
							<div class="col-sm-4">
								<#form:input path="codingDesc" maxlength="100" class="form-control" readonly="true"/>
							</div>
						</div>
					</div>
				</div>
			</div>
			<div class="box-footer">
				<div class="row">
					<div class="col-sm-offset-2 col-sm-10">
						<% if (hasPermi('codingrule:header:edit')){ %>
							<button id="btnSubmit" type="submit" class="btn btn-sm btn-primary" ><i class="fa fa-check"></i> ${text('保 存')}</button>&nbsp;
						<% } %>
						<button type="button" class="btn btn-sm btn-default" id="btnCancel" onclick="js.closeCurrentTabPage()"><i class="fa fa-reply-all"></i> ${text('关 闭')}</button>
					</div>
				</div>
			</div>
		</#form:form>
	</div>
</div>
<% } %>
<script>
//# // 初始化编码规则行表DataGrid对象
$('#linesDataGrid').dataGrid({

	data: "#{toJson(codingRuleHeader.linesList)}",
	datatype: 'local', // 设置本地数据
	autoGridHeight: function(){return 'auto'}, // 设置自动高度
	
	//# // 设置数据表格列
	columnModel: [
		{header:'状态', name:'status', editable:true, hidden:true},
		{header:'主键', name:'autoId', editable:true, hidden:true},
		{header:'${text("编码规则头表ID")}', name:'headerId.autoId', editable:true, hidden:true},
		{header:'<span style="color: red">*</span>${text("类型")}', name:'codingType', width:150, editable:true, edittype:'select',align: "center",
			editoptions:{'class': 'form-control required',
                items: $.merge([{
                    dictLabel: '&nbsp;',
                    dictValue: ''
                }], "#{@DictUtils.getDictListJson('coding_type')}"),
                itemLabel: 'dictLabel', itemValue: 'dictValue',
                dataInit: function (element) {
                    js.select2(element).on("change", function () {
                        $(this).resetValid();
                        let getDataIDs = $('#linesDataGrid').dataGrid('getDataIDs');
                        let getSelectRow = $('#linesDataGrid').dataGrid('getSelectRow');
                        let date = new Date();
                        for (let i = 0; i < getDataIDs.length; i++) {
                            let dataID = getDataIDs[i];

                            if (getSelectRow == dataID) {
                                let currentCodingType = $('#' + dataID + '_codingType').val();
                                if (currentCodingType == 2) { //流水号

                                    //先重置原有的值
                                    $('#' + dataID + '_codingValue').val('');
                                    $('#' + dataID + '_sourceValue').val('');
                                    $('#' + dataID + '_beginValue').val('');
                                    $('#' + dataID + '_length').val('');

                                    //设置为只读
                                    $('#' + dataID + '_codingValue').attr("readOnly", true);
                                    $('#' + dataID + '_sourceValue').attr("disabled", true);
                                    $('#' + dataID + '_beginValue').attr("readOnly", true);
                                    $('#' + dataID + '_length').attr("readOnly", false);

                                }else if (currentCodingType == 1) { // 手工输入
                                    console.log("currentCodingType:"+currentCodingType);
                                    console.log("sourceValue:"+$('#' + dataID + '_sourceValue').val());
                                    //先重置原有的值
                                    $('#' + dataID + '_codingValue').val('');
                                    $('#' + dataID + '_sourceValue').val('');
                                    $('#' + dataID + '_beginValue').val('');
                                    $('#' + dataID + '_length').val('');

                                    //设置新值
                                    // $('#' + dataID + '_codingValue').val('');

                                    //起始值不可编辑
                                    $('#' + dataID + '_codingValue').attr("readOnly", false);
                                    $('#' + dataID + '_sourceValue').attr("disabled", true);
                                    $('#' + dataID + '_beginValue').attr("readOnly", true);
                                    $('#' + dataID + '_length').attr("readOnly", true);

                                }else if (currentCodingType == 3) { // 4位年
                                    console.log("currentCodingType:"+currentCodingType);
                                    console.log("sourceValue:"+$('#' + dataID + '_sourceValue').val());
                                    //先重置原有的值
                                    $('#' + dataID + '_codingValue').val('');
                                    $('#' + dataID + '_sourceValue').val('');
                                    $('#' + dataID + '_beginValue').val('');
                                    $('#' + dataID + '_length').val('');

                                    //设置新值
                                    // $('#' + dataID + '_codingValue').val('');

                                    //起始值不可编辑
                                    $('#' + dataID + '_codingValue').attr("readOnly", false);
                                    $('#' + dataID + '_sourceValue').attr("disabled", false);
                                    $('#' + dataID + '_beginValue').attr("readOnly", true);
                                    $('#' + dataID + '_length').attr("readOnly", true);

                                } else if (currentCodingType == 4) { //2位年

                                    //先重置原有的值
                                    $('#' + dataID + '_codingValue').val('');
                                    $('#' + dataID + '_sourceValue').val('');
                                    $('#' + dataID + '_beginValue').val('');
                                    $('#' + dataID + '_length').val('');

                                    $('#' + dataID + '_sourceValue').attr("disabled", false);
                                    $('#' + dataID + '_codingValue').attr("readOnly", true);
                                    $('#' + dataID + '_beginValue').attr("readOnly", true);
                                    $('#' + dataID + '_length').attr("readOnly", true);

                                } else if (currentCodingType == 5){ //2位月

                                    //先重置原有的值
                                    $('#' + dataID + '_codingValue').val('');
                                    $('#' + dataID + '_sourceValue').val('');
                                    $('#' + dataID + '_beginValue').val('');
                                    $('#' + dataID + '_length').val('');

                                    $('#' + dataID + '_sourceValue').attr("disabled", false);
                                    $('#' + dataID + '_codingValue').attr("readOnly", true);
                                    $('#' + dataID + '_beginValue').attr("readOnly", true);
                                    $('#' + dataID + '_length').attr("readOnly", true);

                                } else if (currentCodingType == 6){ //2位日

                                    //先重置原有的值
                                    $('#' + dataID + '_codingValue').val('');
                                    $('#' + dataID + '_sourceValue').val('');
                                    $('#' + dataID + '_beginValue').val('');
                                    $('#' + dataID + '_length').val('');

                                    $('#' + dataID + '_sourceValue').attr("disabled", false);
                                    $('#' + dataID + '_codingValue').attr("readOnly", true);
                                    $('#' + dataID + '_beginValue').attr("readOnly", true);
                                    $('#' + dataID + '_length').attr("readOnly", true);

                                } else if (currentCodingType == '' || currentCodingType == null || currentCodingType == undefined) {
	                                $('#' + dataID + '_codingValue').val('');
	                                $('#' + dataID + '_sourceValue').val('');
	                                $('#' + dataID + '_beginValue').val('');
	                                $('#' + dataID + '_length').val('');
                                }
                            }
                        }
                    });
                }
            }
        },
		{header:'${text("来源值")}', name:'sourceValue', width:150, editable:true, edittype:'select',
            editoptions: {
                'class': 'form-control',
                items: $.merge([{
                    dictLabel: '&nbsp;',
                    dictValue: ''
                }], ${@DictUtils.getDictListJson('source_value')}),
                itemLabel: 'dictLabel', itemValue: 'dictValue', dataInit: function (element) {
                    $(element).select2().on("change", function () {
                        $(this).resetValid()
                    });
                },
                dataInit: function (element) {
                    $(element).on('change', function (element) {
                        let getSelectRow = $('#linesDataGrid').dataGrid('getSelectRow');
                        let currentCodingType = $('#' + getSelectRow + '_codingType').val();
                        console.log(currentCodingType)
                        if (currentCodingType == '' || currentCodingType==null || currentCodingType==undefined){
                            // 去除选中的值
                            $('#' + getSelectRow + '_codingType').attr("selected",true);
                            $('#' + getSelectRow + '_codingType').change();
                            js.showMessage("请先设置类型才能设置来源值",{time: 2000,icon:0})
                            return;
                        }
                    })
                }
            }
		},
		{header:'${text("设置值")}', name:'codingValue', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'10', 'class':'form-control'}},
		{header:'${text("长度")}', name:'length', width:150, editable:true, edittype:'text',align: "center",
            editoptions: {
                'maxlength': '200', 'class': 'form-control number', 'readonly': 'true',
                dataInit: function (element) {
                    $(element).on('change', function (element) {
                        let getDataIDs = $('#linesDataGrid').dataGrid('getDataIDs');
                        let getSelectRow = $('#linesDataGrid').dataGrid('getSelectRow');
                        for (let i = 0; i < getDataIDs.length; i++) {
                            let dataID = getDataIDs[i];
                            if (getSelectRow == dataID) {
                                $('#' + dataID + '_length').addClass('number');

                                let length = $('#' + getSelectRow + '_length').val();
                                let r = /^\+?[1-9][0-9]*$/;　//正整数的正则表达式
                                if (length != null && length != '' && length != undefined) {
                                    let flag = r.test(length);
                                    if (!flag) {
                                        layer.alert('长度只能输入正整数');
                                    } else {
                                        let beginValue = getNum(1, Number(length));
                                        //根据输入的长度，动态展示起始值
                                        $('#' + dataID + '_beginValue').val(beginValue);
                                    }
                                }
                            }
                        }
                    })
                }
            }
		},
		{header:'${text("起始值")}', name:'beginValue', width:150, editable:true, edittype:'text', editoptions:{'maxlength':'20', 'class':'form-control','readonly': 'true'}},
		{header:'${text("分隔符")}', name:'separator', width:150, editable:true, edittype:'select', align: "center", editoptions: {
            'class': 'form-control',
            items: $.merge([{
                dictLabel: '&nbsp;',
                dictValue: ''
            }], "#{@DictUtils.getDictListJson('separator')}"),
            itemLabel: 'dictLabel', itemValue: 'dictValue', dataInit: function (element) {
                js.select2(element).on("change", function () {
                    $(this).resetValid()
                });
            }
        }
		},
		{header:'${text("操作")}', name:'actions', width:80, align:'center', formatter: function(val, obj, row, act){
			let actions = [];
			if (val == 'new'){
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#linesDataGrid\').dataGrid(\'delRowData\',\''+obj.rowId+'\')});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}else{
				actions.push('<a href="#" onclick="js.confirm(\'${text("你确认要删除这条数据吗？")}\', function(){$(\'#linesDataGrid\').dataGrid(\'setRowData\',\''+obj.rowId+'\',null,{display:\'none\'});$(\'#'+obj.rowId+'_status\').val(\''+Global.STATUS_DELETE+'\');});return false;"><i class="fa fa-trash-o"></i></a>&nbsp;');
			}
			return actions.join('');
		}, editoptions: {defaultValue: 'new'}}
	],
	
	//# // 编辑表格参数
	editGrid: true,				// 是否是编辑表格
	editGridInitRowNum: 1,		// 编辑表格的初始化新增行数
	editGridAddRowBtn: $('#linesDataGridAddRowBtn'),	// 子表增行按钮
	editGridAddRowBtnToHeader: false,	// 子表增行按钮是否显示到表头上
	editGridAddRowInitData: {autoId: '', status: Global.STATUS_NORMAL},	// 新增行的时候初始化的数据

	//# // 编辑表格的提交数据参数
	editGridInputFormListName: 'linesList', // 提交的数据列表名
	editGridInputFormListAttrs: 'status,autoId,headerId.autoId,seq,codingType,codingValue,sourceValue,length,beginValue,separator,remarks,createBy,createDate,updateBy,updateDate,', // 提交数据列表的属性字段
	
	//# // 加载成功后执行事件
	ajaxSuccess: function(data){
		
	}
});


    /**
     * 初始化显示
     */
    $(function () {
        let objectType = $("#objectType").val();
        if (objectType ==='0'){  //单据类型
            $('#formIdHide').show();	//显示
            $('#barcodeTypeHide').hide();	//隐藏
            $('#barcodeType').val("");//条码类型
            $('#formId').val("");	//表单名称
            $('#codingType').val("");	//编码方式
        } else {
            $('#formIdHide').hide();
            $('#barcodeTypeHide').show();
        }
    });

    /**
     * 改变下拉框显示
     */
    $("#objectType").change(function () {
        let objectType = $("#objectType").val();
        if (objectType ==='0'){
            $('#formIdHide').show();
            $('#barcodeTypeHide').hide();
            $('#barcodeType').val("");
        } else if (objectType ==='1'){
            $('#formIdHide').hide();
            $('#barcodeTypeHide').show();
        }
    })

    /**
     * 前端JS如何实现数字前面补充000000
     */
    function getNum(num, n) {
        let value = Array(n).join(0) + num;
        return value.slice(-n);
    }

    /**
     * 保存
     */
    $('#btnSubmit').click(function () {
        // 保存前恢复编辑行
        let ids = $('#linesDataGrid').dataGrid('getDataIDs');
        for (let i=0;i<ids.length;i++) {
            //恢复编辑行
            $('#linesDataGrid').dataGrid('editRow', ids[i], {keys:true, focusField:false});
        }
        $('#inputForm').submit();
    });


</script>

<script>
    $('#inputForm').validate({
        /*invalidHandler: function(form, validator) {
            // 获取未通过验证的字段
            let invalidFields = validator.invalid;
            console.log("未通过验证的字段:", invalidFields);
        },*/
        submitHandler: function(form){
            console.log("保存2");
            js.ajaxSubmitForm($(form), function(data){
                js.showMessage(data.message);
                if(data.result == Global.TRUE){
                    js.closeCurrentTabPage(function(contentWindow){
                        contentWindow.page();
                    });
                }
            }, "json");
        }
    });
</script>